package com.zframeworks.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry webSocketHandlerRegistry) {
        //WebSocket连接地址 ws://IP地址/im  允许跨域
        webSocketHandlerRegistry.addHandler(webSocketHandler,"/im").setAllowedOrigins("*")
                //添加监听获取参数，获取登录账号与密码
                .addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, org.springframework.web.socket.WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
                        String userid = ((ServletServerHttpRequest)serverHttpRequest).getServletRequest().getParameter("userid");
                        if(z.isNotNull(userid)){
                            map.put("userid",userid.toUpperCase());

                            String name = ((ServletServerHttpRequest)serverHttpRequest).getServletRequest().getParameter("name");
                            if(z.isNotNull(name)){
                                map.put("name",name.toUpperCase());
                            }
                        }
                        return true;
                    }
                    @Override
                    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, org.springframework.web.socket.WebSocketHandler webSocketHandler, Exception e) {
                    }
                });
    }


}
